package org.sendvox.freswitch.core.impl;

import java.util.ArrayList;
import java.util.List;

import org.sendvox.freswitch.core.CommandException;
import org.sendvox.freswitch.core.EventCommand;
import org.sendvox.freswitch.event.Event;
import org.sendvox.freswitch.inbound.InboundClient;
import org.sendvox.freswitch.outbound.OutboundClient;
import org.sendvox.freswitch.util.Arguments;

public final class EventCommandImpl implements EventCommand {

	private static final String SPACE = " ";

	private Type eventType;
	private List<Object> eventList = new ArrayList<Object>();
	private final StringBuilder cmdBuilder = new StringBuilder();
	private InboundClient inboundClient;
	private OutboundClient outboundClient;

	public EventCommandImpl(InboundClient inboundClient) {
		Arguments.INSTANCE.validate(inboundClient).isNotNull();
		this.inboundClient = inboundClient;
	}

	public EventCommandImpl(OutboundClient outboundClient) {
		Arguments.INSTANCE.validate(outboundClient).isNotNull();
		this.outboundClient = outboundClient;
	}

	EventCommandImpl() {
	}

	/**
	 * @param eventCommand
	 *            the eventCommand to set
	 */
	@Override
	public EventCommand type(Type eventType) {
		Arguments.INSTANCE.validate(eventType).isNotNull();
		this.eventType = eventType;
		cmdBuilder.append(eventType.getLiteral().concat(SPACE));
		return this;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.sendvox.freswitch.core.impl.ApiCommand#arg(java.lang.Object)
	 */
	@Override
	public EventCommand list(Event... eventArgs) {
		Arguments.INSTANCE.validate(eventArgs.toString()).isNotNull()
				.isNotEmpty();
		for (Event event : eventArgs) {
			eventList.add(event.getLiteral());
			cmdBuilder.append(event.toString().concat(SPACE));
		}
		return this;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.sendvox.freswitch.core.impl.EventCommand#arg(java.lang.Object)
	 */
	@Override
	public EventCommand custom(Object... args) {
		Arguments.INSTANCE.validate(args).isNotNull().isNotEmpty();
		for (Object arg : args) {
			eventList.add(arg);
			cmdBuilder.append(arg.toString().concat(SPACE));
		}
		return this;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.sendvox.freswitch.core.impl.EventCommand#execute()
	 */
	@Override
	public EventCommand execute() throws CommandException {
		if (inboundClient != null)
			inboundClient.execute(cmdBuilder.toString());
		else if (outboundClient != null)
			outboundClient.execute(cmdBuilder.toString());
		return this;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.sendvox.freswitch.core.impl.EventCommand#getEventList()
	 */
	@Override
	public List<Object> getEventList() {
		return eventList;
	}

	/**
	 * @return the eventType
	 */
	public Type getEventType() {
		return eventType;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "EventCommandImpl [command = " + cmdBuilder + "]";
	}
}
